import { FC, useEffect, useState, useRef } from "react";
import { observer, inject } from "mobx-react";
import * as echarts from "echarts/core";
import { PieChart, PieSeriesOption } from "echarts/charts";
import { LabelLayout } from "echarts/features";
import { SVGRenderer } from "echarts/renderers";

import { ITStore } from "../../store";
import { ITDReactReagent } from "../../store/interfaces";

interface TProp {
  store: ITStore;
  height: number;
  data: ITDReactReagent[];
}

interface ITRendData {
  name: string;
  value: number;
}

type EChartsOption = echarts.ComposeOption<PieSeriesOption>;

echarts.use([PieChart, SVGRenderer, LabelLayout]);

const grayColor = ["#ddd"];

const defaultColor = [
  "#1890ff",
  "#c5effd",
  "#71d2f2",
  "#77b5fe",
  "#28247b",
  "#00FFFF",
  "#7FFF00",
  "#9370DB",
  "#48D1CC",
  "#7B68EE",
  "#ADFF2F",
];

const ReactorChart: FC<TProp | any> = ({
  store,
  height,
  data,
}: TProp): JSX.Element => {
  const domRef = useRef<HTMLDivElement | null>(null);

  const [renderData, setRenderData] = useState<ITRendData[]>([]);

  useEffect(() => {
    let tempData: ITRendData[] = [];
    if (data && data.length) {
      data.forEach((item) => {
        const { reagentid, volume, weight, type, mmol } = item;
        let amount = mmol;
        if (!mmol) {
          if (type === 1) {
            amount = volume;
          } else if (type === 2) {
            amount = weight;
          }
        }
        tempData.push({
          name: reagentid,
          value: amount,
        });
      });
    }
    setRenderData(tempData);
  }, [data]);

  useEffect(() => {
    if (domRef.current) {
      let chartDom = echarts.getInstanceByDom(domRef.current);
      if (!chartDom) {
        chartDom = echarts.init(domRef.current);
      }

      const option: EChartsOption = {
        // color: grayColor,
        series: [
          {
            name: "",
            type: "pie",
            radius: ["88%", "100%"],
            avoidLabelOverlap: false,
            // scale: false,
            label: {
              show: false,
            },
            labelLine: {
              show: false,
            },
            data: renderData,
          },
        ],
      };
      if (!renderData.length) {
        option.color = grayColor;
      } else {
        option.color = defaultColor;
      }
      // chartDom.clear()
      chartDom.setOption(option);
    }
  }, [renderData]);

  return <div ref={domRef} style={{ height: height, width: height }} />;
};

export default inject("store")(observer(ReactorChart));
